import axios from "axios";
import qs from "qs"

function isAcceptJson(config) {
  const accept = getHeaderByName(config.headers || {}, "accept") ||
      "text/html,application/xhtml+xml,application/xml,*/*";
  return accept.split(",").map( item => (item.split(";"))[0] )
      .includes("application/json");
}

function getHeaderByName(headers, headerName) {
  headers = headers || {};
  headerName = headerName.toLowerCase();
  for (const name in headers) {
    if (headerName == name.toLowerCase()) {
      return headers[name];
    }
  }
  return "";
}

function setConfig(config, method) {
  config = config || {};
  config.method = method;
  config.baseURL = location.protocol + "//" + location.hostname +
      ((location.protocal === "https" && location.port !== 443) ||
          (location.protocal === "http" && location.port !== 80) ? ":" + location.port : "") + "/";
  config.transformRequest = [function (data, headers) {
    if (getHeaderByName(headers, "content-type") === "application/json") {
      return JSON.stringify(data);
    }
    return qs.stringify(data);
  }];
  return config;
}

axios.interceptors.response.use(
    function (response) {
      return response;
    },
    function (error) {
      console.log(error);
      if (error && error.response && error.response.staus == 401) {
        alert("You session has been expired, please log in again");
        location.href = "/";
      } else {
        throw error;
      }
    }
);

export default {
  get(config) {
    return axios(setConfig(config, 'get'));
  },
  post(config) {
    return axios(setConfig(config, 'post'));
  },
  sendJSON(config) {
    config.headers = config.headers || {};
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  receiveJSON(config) {
    config.headers = config.headers || {};
    config.headers["Accept"] = "application/json,text/plain,*/*";
    return config;
  }
};
